from rest_framework import serializers

from api.models import District
from record.models import Car, Record


class DistrictSerializer(serializers.ModelSerializer):
    """地区序列化器"""

    class Meta:
        model = District
        exclude = ('parent', 'ishot')


class DistrictDetailSerializer(serializers.ModelSerializer):
    """地区详情序列化器"""
    cities = serializers.SerializerMethodField()

    @staticmethod
    def get_cities(district):
        queryset = District.objects.filter(parent=district)
        return DistrictSerializer(queryset, many=True).data

    class Meta:
        model = District
        fields = ('distid', 'name', 'intro', 'cities')


class CarSerializer(serializers.ModelSerializer):
    """汽车序列化器"""

    class Meta:
        model = Car
        fields = '__all__'


class CarSimpleSerializer(serializers.ModelSerializer):

    class Meta:
        model = Car
        fields = ('carno', 'owner')


class RecordSerializer(serializers.ModelSerializer):
    """违章记录序列化器"""
    makedate = serializers.SerializerMethodField()
    car = serializers.SerializerMethodField()

    @staticmethod
    def get_makedate(record):
        return record.makedate.strftime('%Y-%m-%d %H:%M')

    @staticmethod
    def get_car(record):
        return CarSimpleSerializer(record.car).data

    class Meta:
        model = Record
        fields = '__all__'
